package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     * 1.新增套餐（包括套餐菜品关系）
     * @param setmealDTO
     */
    @Override
    @Transactional //多表操作，开启事务
    public void saveWithDish(SetmealDTO setmealDTO) {
        //1.向套餐表setmeal插入数据
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealMapper.insert(setmeal);

        //2.向套餐菜品关系表setmeal_dish插入数据
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes(); //获取前端传递的套餐菜品关系集合
        //判断集合是否为空
        if (setmealDishes != null && setmealDishes.size() > 0) {
            Long setmealId = setmeal.getId(); //获取插入数据后返回的套餐id
            for (SetmealDish setmealDish : setmealDishes) {
                setmealDish.setSetmealId(setmealId); //补上套餐id
            }
            //向套餐菜品关系表批量添加数据
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    /**
     * 2.套餐分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        //动态条件查询
        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);
        //封装结果并返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 3.批量删除套餐(同时需要删除套餐菜品关系)
     * @param ids
     */
    @Override
    @Transactional //多表操作，开启事务
    public void deleteBatch(Long[] ids) {
        //1、启售中的套餐不可删除
        for (Long id : ids) {
            //根据套餐id查询套餐表数据
            Setmeal setmeal = setmealMapper.selectById(id);
            //判断是否启售
            if (setmeal.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        //2、删除套餐，同时需要删除相关的菜品关系数据
        for (Long id : ids) {
            setmealMapper.deleteById(id);
            setmealDishMapper.deleteBySetmealId(id);
        }
    }

    /**
     * 4.根据套餐id查询套餐(含菜品关系详情。回显)
     * @param id
     * @return
     */
    @Override
    public SetmealVO getByIdWithDish(Long id) {
        //1、根据套餐id查询套餐表数据
        Setmeal setmeal = setmealMapper.selectById(id);
        //2、根据套餐id查询套餐菜品关系数据
        List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(id);
        //3、将查询结果封装为VO对象
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    /**
     * 5.修改套餐
     * @param setmealDTO
     */
    @Override
    @Transactional //多表操作，开启事务
    public void updateWithDish(SetmealDTO setmealDTO) {
        //1.修改套餐表数据（需要修改公共字段）
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealMapper.update(setmeal);

        //获取前端传递的套餐id
        Long id = setmealDTO.getId();
        //2.因为菜品关系变化情况多，所以直接先删除旧数据
        setmealDishMapper.deleteBySetmealId(id);

        //3.重新添加套餐菜品关系数据
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        //判断集合是否为空
        if (setmealDishes != null && setmealDishes.size() > 0) {
            //为套餐菜品关系实体对象补上套餐id（前端未传递）
            setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(id));
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    /**
     * 6.套餐启售、停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //若想启售套餐，套餐内不能有停售菜品
        if (status == StatusConstant.ENABLE) {
            //1.根据套餐id查询出对应的菜品关系数据
            List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(id);
            //2.遍历菜品关系数据，根据菜品id查询菜品数据，判断菜品是否停售
            if (setmealDishes != null && setmealDishes.size() > 0) {
                for (SetmealDish setmealDish : setmealDishes) {
                    Dish dish = dishMapper.selectById(setmealDish.getDishId());
                    if (dish.getStatus() == StatusConstant.DISABLE) {
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                }
            }
        }
        //调用通用更新方法，修改套餐状态
        Setmeal setmeal = Setmeal.builder().id(id).status(status).build();
        setmealMapper.update(setmeal);
    }

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
}
